/*
 *
 *  Copyright (C) THL A29 Limited, a Tencent company. All rights reserved.
 *  SPDX-License-Identifier: Apache-2.0
 *
 */
import React, { useContext, useEffect } from 'react';
import { Button, Form, Input, InputNumber, Modal, Select } from 'tea-component';
import { Controller, useForm } from 'react-hook-form';
import formUtils, { Validator } from 'src/utils/form-utils';
import { useFetchNodeXl } from 'src/common/apis/chains/hooks';
import { saveNode } from 'src/common/apis/certificates/hooks';

import { ChainDetailContext } from '../chain-detail';

const { getStatus } = formUtils;

interface IGenerateCertModalParam {
  visible: boolean;
  close: () => void;
  successCallback?: () => void;
}

interface IInitialData {
  ChainId: string;
  NodeName: string;
  StorageSize: number;
}

const initialData: IInitialData = {
  ChainId: '',
  StorageSize: Validator.defaultStorageSize,
  NodeName: '',
};

export function AddNodeModal({ visible, close, successCallback }: IGenerateCertModalParam) {
  const { chainId } = useContext(ChainDetailContext);
  const {
    control,
    reset,
    handleSubmit,
    formState: { errors, isValidating, isSubmitting, isSubmitted, isValid },
  } = useForm({
    mode: 'onBlur',
    defaultValues: {
      StorageSize: Validator.defaultStorageSize,
    } as any,
  });

  const { orgList, run: fetchNodeListX } = useFetchNodeXl();
  const { fetch: fetchSaveNode } = saveNode();
  const submit = async (values: IInitialData) => {
    await fetchSaveNode({
      ChainId: chainId,
      NodeName: values.NodeName,
      StorageSize: values.StorageSize,
    });
    successCallback?.();
  };

  useEffect(() => {
    if (visible) {
      reset();
      // getNode();
      fetchNodeListX(chainId || undefined);
    }
  }, [visible]);

  return (
    <Modal caption="添加节点" visible={visible} onClose={close}>
      <Modal.Body>
        <Form>
          <Controller
            name="NodeName"
            control={control}
            rules={{
              validate: (NodeName) => {
                if (NodeName === null || NodeName === undefined) {
                  return '请选择节点';
                }
              },
            }}
            render={({ field, fieldState }) => (
              <Form.Item
                label="节点选择"
                required
                status={isValidating ? 'validating' : getStatus({ fieldState, isSubmitted, isValidating })}
                message={errors.NodeName?.message}
              >
                <Select
                  placeholder="请选择节点"
                  type="simulate"
                  appearance="button"
                  options={
                    orgList
                      ? orgList.map((item) => ({
                          text: item.NodeName,
                          value: item.NodeName,
                        }))
                      : []
                  }
                  size="full"
                  {...field}
                />
              </Form.Item>
            )}
          />
          <Controller
            name="StorageSize"
            control={control}
            render={({ field, fieldState }) => (
              <Form.Item
                label="存储容量"
                required
                status={getStatus({ fieldState, isSubmitted, isValidating })}
                message={errors.StorageSize?.message}
              >
                <InputNumber
                  min={Validator.minStorageSize}
                  max={Validator.maxStorageSize}
                  unit={'Gb'}
                  size={'l'}
                  {...field}
                />
              </Form.Item>
            )}
          />
        </Form>
      </Modal.Body>
      <Modal.Footer>
        <Button type="primary" disabled={isSubmitting || !isValid} onClick={handleSubmit(submit)}>
          确定
        </Button>
        <Button onClick={close}>取消</Button>
      </Modal.Footer>
    </Modal>
  );
}
